"""
Created on 27-Jul-2009

@author: dexen
"""

import socket

import rpyc

default_config = {
    "allow_pickle":True,
    "instantiate_custom_exceptions":True,
    "instantiate_oldstyle_exceptions":True
}

REGISTRY_PORT = 9999
MAX_SLAVE_SLOTS = 4 # The number of 

class DexenAddr(object):
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
   
    def get_conn(self, conf=default_config):
        return rpyc.connect(self.ip, self.port, config=conf)

def get_my_ip(is_local=False):
    if is_local: return "127.0.0.1"
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(("gmail.com", 80))
    except socket.gaierror:
        return "127.0.0.1"
    return s.getsockname()[0]

def get_reg_addr(reg_ip):
    return DexenAddr(reg_ip, REGISTRY_PORT)

def get_reg_conn(reg_ip):
    reg_addr = DexenAddr(reg_ip, REGISTRY_PORT)
    return reg_addr.get_conn()

def get_svr_addr(reg_ip):
    reg_conn = get_reg_conn(reg_ip)
    srv_addr = reg_conn.root.get_server_addr()
    srv_addr = rpyc.classic.obtain(srv_addr)
    return srv_addr

def get_svr_conn(reg_ip):
    srv_addr = get_svr_addr(reg_ip)
    return srv_addr.get_conn()

class MyService(rpyc.Service):  
    def on_connect(self):
        print "Somebody connected."
    
    def on_disconnect(self):
        print "Somebody disconnected."
    
    def _rpyc_getattr(self, name):
        if not name.startswith("_"):
            return getattr(self, name)
        else:
            raise AttributeError("private attributes are not accessible.")
    
    def _rpyc_setattr(self, name, value):
        print "I am in setattr", name, value
        if not name.startswith("_"):
            return setattr(self, name, value)
        else:
            raise AttributeError("private data attributes cannot be set.")
    
